package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceReportsDataVO;
import com.zzyl.nursing.vo.ProductVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 设备Service业务层处理
 *
 * @author alexis
 * @date 2025-03-06
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     *
     * @param deviceDto 设备
     * @return 结果
     */
    @Override
    public void updateDevice(DeviceDto deviceDto) {
        // 校验参数
        if (this.lambdaQuery().ne(Device::getNodeId, deviceDto.getNodeId())
                .eq(Device::getDeviceName, deviceDto.getDeviceName()).count() > 0) {
            throw new BaseException("设备名称已存在，请重新输入");
        }
        if (this.lambdaQuery().eq(Device::getProductKey, deviceDto.getProductKey())
                .ne(Device::getNodeId, deviceDto.getNodeId())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation()).
                count() > 0) {
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
        this.updateDeviceFromIot(deviceDto);
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        try {
            deviceMapper.updateById(device);
        } catch (Exception e) {
            // 用数据库原来的设备数据更新Iot平台数据
            device = this.lambdaQuery().eq(Device::getId, deviceDto.getId()).one();
            deviceDto = BeanUtil.toBean(device, DeviceDto.class);
            this.updateDeviceFromIot(deviceDto);
            throw new BaseException("本地数据库-更新设备失败");
        }
    }

    /**
     * 更新Iot平台设备
     *
     * @param deviceDto
     */
    private void updateDeviceFromIot(DeviceDto deviceDto) {
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        request.withBody(body);
        UpdateDeviceResponse response;
        try {
            response = client.updateDevice(request);
            if (response.getHttpStatusCode() != 200) {
                throw new BaseException("物联网接口-修改设备数据失败:" + response.getHttpStatusCode());
            }
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        // 请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        // 设置条数
        listProductsRequest.setLimit(50);
        // 发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败:" + response.getHttpStatusCode());
        }
        // 存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String string = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if (StrUtil.isEmpty(string)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(string, ProductVo.class);
    }

    /**
     * 注册产品
     */
    @Override
    public void add(DeviceDto deviceDto) {
        // 校验参数
        if (this.lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count() > 0) {
            throw new BaseException("设备名称已存在，请重新输入");
        }
        if (this.lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()).count() > 0) {
            throw new BaseException("设备标识码已存在，请重新输入");
        }
        if (this.lambdaQuery().eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation()).
                count() > 0) {
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
        // 密钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        // iot中新增设备
        AddDeviceResponse response = addToIot(deviceDto, secret);
        // 数据库中新增设备
        // 属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        // 设备id、设备绑定状态
        device.setIotId(response.getDeviceId());
        // 秘钥
        device.setSecret(secret);
        try {
            save(device);
        } catch (Exception e) {
            // 删除Iot新增设备
            this.deleteDeviceFromIotByIotId(response.getDeviceId());
            throw new BaseException("本地数据库-新增设备失败");
        }
    }

    /**
     * 向Iot中新增设备
     *
     * @param deviceDto
     * @param secret
     * @return
     */
    @NotNull
    private AddDeviceResponse addToIot(DeviceDto deviceDto, String secret) {
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        AuthInfo authInfo = new AuthInfo();
        authInfo.withAuthType("SECRET")
                .withSecret(secret)
                .withSecureAccess(true);
        body.withAuthInfo(authInfo);
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());
        request.withBody(body);
        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
            if (response.getHttpStatusCode() != 201) {
                throw new BaseException("物联网接口-注册设备失败:" + response.getHttpStatusCode());
            }
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
        return response;
    }

    @Override
    public DeviceDetailVo findByIotId(String iotId) {
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        DeviceDetailVo deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
            if (response.getHttpStatusCode() != 200) {
                throw new BaseException("物联网接口-查询设备信息失败:" + response.getHttpStatusCode());
            }
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
        deviceVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StrUtil.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceVo.setActiveTime(activeTime);
        }
        return deviceVo;
    }

    /**
     * 查看设备上报的数据
     */
    @Override
    public List<DeviceReportsDataVO> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response;
        try {
            response = client.showDeviceShadow(request);
            if (response.getHttpStatusCode() != 200) {
                throw new BaseException("物联网接口-查询设备上报数据失败" + response.getHttpStatusCode());
            }
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            return List.of();
        }
        DeviceShadowProperties reported = shadow.get(0).getReported();
        if (ObjUtil.isNull(reported)) {
            return List.of();
        }
        ArrayList<DeviceReportsDataVO> deviceReportsDataVOS = new ArrayList<>();
        JSONObject properties = JSONUtil.parseObj(reported.getProperties());
        String eventTimeStr = reported.getEventTime();
        LocalDateTime activeTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        properties.forEach((k, v) -> deviceReportsDataVOS.add(new DeviceReportsDataVO(k, eventTime, v)));
        return deviceReportsDataVOS;
    }

    @Override
    public void deleteDeviceByIotId(String iotId) {
        deleteDeviceFromIotByIotId(iotId);
        try {
            this.remove(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
        } catch (Exception e) {
            // 根据数据库数据重新向iot平台插入删除的设备数据
            Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
            String secret = device.getSecret();
            DeviceDto deviceDto = BeanUtil.toBean(device, DeviceDto.class);
            this.addToIot(deviceDto, secret);
            throw new BaseException("本地数据库-删除设备失败");
        }
    }

    /**
     * 从iot平台删除设备
     *
     * @param iotId
     */
    private void deleteDeviceFromIotByIotId(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        try {
            DeleteDeviceResponse response = client.deleteDevice(request);
            if (response.getHttpStatusCode() != 204) {
                throw new BaseException("物联网接口-删除设备失败:" + response.getHttpStatusCode());
            }
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
    }

    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response;
        try {
            response = client.showProduct(request);
            if (response.getHttpStatusCode() != 200) {
                throw new BaseException("物联网接口-查询设备上报数据失败" + response.getHttpStatusCode());
            }
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollUtil.isEmpty(serviceCapabilities)){
            return null;
        }
        return serviceCapabilities;
    }
}
